'use strict';

const BaseController = require('./base');


const fs = require('fs');

const path = require('path');

const awaitWriteStream = require('await-stream-ready').write;

const sendToWormhole = require('stream-wormhole');

const md5 = require('md5');

class FileController extends BaseController {
  async index() {
    const ctx = this.ctx;
    // 处理文件六
    const stream = await ctx.getFileStream();
    // 新建一个文件名
    const filename = md5(stream.filename) + path
      .extname(stream.filename)
      .toLocaleLowerCase();
    // 文件生成绝对路径
    const uploadPath = path.join(this.config.baseDir, 'app/public/uploads');

    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath);
    }
    const target = path.join(uploadPath, filename);
    // 生成一个文件写入 文件流
    const writeStream = fs.createWriteStream(target);
    try {
      // 异步把文件流 写入
      await awaitWriteStream(stream.pipe(writeStream));
    } catch (err) {
      // 如果出现错误，关闭管道
      await sendToWormhole(stream);
      throw err;
    }
    // 文件响应
    ctx.body = {
      url: '/public/uploads/' + filename,
    };
  }
}

module.exports = FileController;
